<template>
  <div style="background-color: #f0f2f5; padding: 0px">
    <PageHeader
      :breadcrumb="breadcrumb"
      style="background-color: white; padding: 24px; margin-bottom: 16px"
    />
    <div style="background-color: white; padding: 24px; padding-top: 0px">
      <div id="operationButton">
        <a-button
          v-if="canAddExperimentInfo"
          size="large"
          type="primary"
          @click="onAddButtonClick"
        >
          添加
        </a-button>
        &nbsp;
        <a-button
            size="large"
            type="primary"
            @click="onRefresh"
        >
          刷新
        </a-button>
        <a-modal
          v-model:visible="addOrEditDialogVisible"
          :title="addOrEditDialogTitle"
          :width="600"
          :keyboard="false"
          :maskClosable="false"
          :footer="null"
          :destroyOnClose="true"
          centered
        >
          <AddOrEditExperimentInfo
            :url="editUrl"
            @operate-success="onAddOrEditSuccess"
            @operate-failed="closeAddOrEditDialog"
          />
        </a-modal>
      </div>
      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="data"
        :pagination="{ pageSize: 10 }"
        :scroll="{ x: 240 }"
      >
        <template #status="{ record }">
          <StatusTag :status="record.status" />
        </template>
        <template
          v-if="
            canAddExperimentInfo ||
            canEditExperimentInfo ||
            canDeleteExperimentInfo
          "
          #operation="{ record }"
        >
          <RequireAuditTableOperation
            :status="record.status"
            :canAdd="canAddExperimentInfo"
            :canEdit="canEditExperimentInfo"
            :canDelete="canDeleteExperimentInfo"
            @submit="onSubmit(record.key)"
            @edit="onEdit(record.key)"
            @delete="onDelete(record.key)"
          />
        </template>
        <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
          <div style="padding: 8px">
            <a-input
                :ref="c => (searchInput = c)"
                :placeholder="`查询 ${column.title}`"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block;"
                @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
                type="primary"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template #icon>
                <SearchOutlined/>
              </template>
              查询
            </a-button>
            <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
              重置
            </a-button>
          </div>
        </template>
        <template #filterIcon="filtered">
          <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }"/>
        </template>
        <template #customRender="{ text, column }">
              <span v-if="searchText && searchedColumn === column.dataIndex">
                <template
                    v-for="(fragment, i) in text
                    .toString()
                    .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
                >
                  <mark
                      v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                      :key="i"
                      class="highlight"
                  >
                    {{ fragment }}
                  </mark>
                  <template v-else>{{ fragment }}</template>
                </template>
              </span>
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>


<script>
import AddOrEditExperimentInfo from "./AddOrEditExperimentInfo";
import RequireAuditTableOperation from "../../Common/RequireAuditTableOperation";
import StatusTag from "../../Common/StatusTag";
import { message } from "ant-design-vue";
import PageHeader from "../../Common/PageHeader";
import {SearchOutlined} from '@ant-design/icons-vue'

const operationColumn = {
  title: "操作",
  dataIndex: "operation",
  slots: { customRender: "operation" },
  width: 200,
};

export default {
  name: "ExperimentInfo",
  emits: ["add"],
  components: {
    AddOrEditExperimentInfo,
    RequireAuditTableOperation,
    StatusTag,
    PageHeader,
    SearchOutlined,
  },
  data() {
    const refreshInterval = 100;
    return {
      breadcrumb: [
        { key: 1, title: "实验过程管理" },
        { key: 2, title: "实验信息" },
      ],
      data: [],
      loading: false,
      addOrEditDialogVisible: false,
      addOrEditDialogTitle: "",
      editUrl: "",
      canAddExperimentInfo: false,
      canEditExperimentInfo: false,
      canDeleteExperimentInfo: false,
      columns: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      refreshInterval,
    };
  },

  mounted() {
    this.columns = this.getDataColumns();
    this.processPermission();
    this.fetch();
  },

  methods: {
    getDataColumns() {
      return [
        {
          title: "实验名称",
          dataIndex: "experiment_name",
          width: 150,
          key: 'experiment_name',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: "课题名称",
          dataIndex: "subject_name",
          width: 150,
          key: 'subject_name',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: "实验编号",
          dataIndex: "experiment_num",
          width: 150,
          key: 'experiment_num',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: "实验人员",
          dataIndex: "experimenter",
          width: 150,
          key: 'experimenter',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: "审核人",
          dataIndex: "experiment_reviewer",
          width: 150,
          key: 'experiment_reviewer',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: "状态",
          dataIndex: "status",
          // key: 'status',
          slots: {
            customRender: "status",
            // filterDropdown: 'filterDropdown',
            // filterIcon: 'filterIcon',
          },
          width: 150,
/*          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },*/
        },
      ];
    },
    // 从后端获取数据
    processPermission() {
      this.axios
        .get("/has_permission?permission=experiment_management.add_experiment")
        .then((res) => {
          this.canAddExperimentInfo = res.data.result;
          let last = this.columns.length;
          if (
            this.columns[last - 1].dataIndex !== "operation" &&
            this.canAddExperimentInfo
          ) {
            this.columns.push(operationColumn);
          }
        })
        .catch((error) => {
          console.log("Error", error.message);
        });
      this.axios
        .get(
          "/has_permission?permission=experiment_management.change_experiment"
        )
        .then((res) => {
          this.canEditExperimentInfo = res.data.result;
          let last = this.columns.length;
          if (
            this.columns[last - 1].dataIndex !== "operation" &&
            this.canEditExperimentInfo
          ) {
            this.columns.push(operationColumn);
          }
        })
        .catch((error) => {
          console.log("Error", error.message);
        });
      this.axios
        .get(
          "/has_permission?permission=experiment_management.delete_experiment"
        )
        .then((res) => {
          this.canDeleteExperimentInfo = res.data.result;
          let last = this.columns.length;
          if (
            this.columns[last - 1].dataIndex !== "operation" &&
            this.canDeleteExperimentInfo
          ) {
            this.columns.push(operationColumn);
          }
        })
        .catch((error) => {
          console.log("Error", error.message);
        });
    },
    fetch() {
      this.loading = true;
      let updateData = [];
      this.axios
        .get("/experiment_management/experiment_information/")
        .then((res) => {
          const data = res.data;
          for (let i = 0; i < data.length; ++i) {
            updateData.push({
              key: data[i].url,
              experiment_name: data[i].experiment_name,
              subject_name: data[i].readable_subject_name,
              experiment_num: data[i].experiment_num,
              experimenter: data[i].experimenter,
              experiment_reviewer: data[i].experiment_reviewer,
              status: data[i].approval_status,
            });
          }
          setTimeout(() => {
            this.data = updateData;
            this.loading = false;
          }, this.refreshInterval);
          // console.log('chemical:', res)
        })
        .catch((error) => {
          setTimeout(() => {
            this.loading = false;
          }, this.refreshInterval);
          console.log("Error", error.message);
        });
    },
    onAddButtonClick() {
      this.addOrEditDialogTitle = "添加实验信息";
      this.editUrl = "";
      this.addOrEditDialogVisible = true;
      // this.$emit('add')
    },
    onAddOrEditSuccess() {
      this.closeAddOrEditDialog();
      this.fetch();
    },
    closeAddOrEditDialog() {
      this.addOrEditDialogVisible = false;
      this.fetch();
    },
    onSubmit(key) {
      this.axios
        .patch(key, { approval_status: "1" })
        .then(() => {
          message.success("提交成功!");
          this.fetch();
        })
        .catch((error) => {
          message.error("提交失败!");
          console.log("Error", error.message);
        });
    },
    onEdit(key) {
      this.addOrEditDialogTitle = "编辑化学性能";
      //console.log(key)
      this.editUrl = key;
      this.addOrEditDialogVisible = true;
    },
    onDelete(key) {
      // console.log("hello", key);
      message.loading({ content: "删除中...", key });
      const data = [...this.data];
      this.axios
        .delete(key)
        .then(() => {
          setTimeout(() => {
            message.success({ content: "删除成功！", key, duration: 2 });
            this.data = data.filter((item) => item.key !== key);
          }, 1000);
        })
        .catch((error) => {
          setTimeout(() => {
            message.error({ content: "删除失败！", key, duration: 2 });
          }, 1000);
          console.log("Error", error.message);
        });
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      // console.log(selectedKeys[0]);
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
      // this.$forceUpdate();
    },
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = '';
    },
    onRefresh() {
      this.fetch()
    },
  },
};
</script>


<style>
#operationButton {
  text-align: right;
  /*padding: 20px;*/
}
</style>